package com.bj.jiufu.base;

import com.sun.xml.internal.ws.addressing.policy.AddressingPolicyMapConfigurator;
import net.sf.json.JSONObject;

import javax.servlet.http.HttpServletRequest;

import static javafx.scene.input.KeyCode.T;
import static net.sf.json.JSONObject.toBean;

public class AbstractBaseController {
    public static String SUCCESS = "0";
    public static String ERROR = "1";

    /**
     * 获取请求内容
     *
     * @param request
     * @return
     */
    public <T> T getBody(HttpServletRequest request, Class<T> clazz) {
        try {
            if (request != null) {
                JSONObject content = (JSONObject) request.getAttribute("content");
                JSONObject body = (JSONObject) content.get("body");
                T ret = (T) JSONObject.toBean(body, clazz);
                return ret;
            }
        } catch(Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取请求内容
     *
     * @param request
     * @return
     */
    public static Header getHeader(HttpServletRequest request) {
        if (request != null) {
            JSONObject content = (JSONObject) request.getAttribute("content");
            JSONObject header = (JSONObject)content.get("header");
            Header ret = (Header)content.toBean(header, Header.class);
            return ret;
        }
        return new Header();
    }

    /**
     * 返回报文
     *
     * @param header
     * @param respParam
     * @return
     */
    public static RespMsg retRespMsg(Header header, RespParam respParam) {
        RespMsg respMsg = new RespMsg();
        if (respParam.isSuccess()) {
            header.setRetStatus(SUCCESS);
        } else {
            header.setRetStatus(ERROR);
        }
        respMsg.setBody(respParam);
        respMsg.setHeader(header);
        return respMsg;
    }

    /**
     * 返回报文
     *
     * @param req
     * @param respParam
     * @return
     */
    public static RespMsg retRespMsg(HttpServletRequest req, RespParam respParam) {
        Header header = getHeader(req);
        RespMsg respMsg = retRespMsg(header, respParam);
        return respMsg;
    }

}
